<template>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field
                v-model="password"
                name="密码"
                label="密码"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />
        </van-cell-group>
        <van-cell-group inset>
            <van-field
                v-model="repassword"
                name="密码"
                label="重复密码"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />
        </van-cell-group>
        <div style="margin: 16px">
            <van-button
                :disabled="btnFlage" 
                round 
                block 
                type="primary" 
                native-type="submit"
            >
                注册
            </van-button>
        </div>
    </van-form>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { Ref } from 'vue'
import { dofinishregister } from "@/api/register";
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter } from "vue-router";

// 创建一个 选项式 API 中的 this.$router
const router = useRouter()

// 存储用户输入的密码
const password: Ref<string> = ref('')

// 存储用户再次输入的密码
const repassword: Ref<string> = ref('')

async function onSubmit() {
    // console.log('注册成功');
    const { data } = await dofinishregister({
        tel: window.localStorage.getItem('phoneNum'),
        password: password.value
    }) 
    if (data.code !== '200') {
        // 提示用户验证码错误
        return showFailToast(data.message);
    }

    // 提醒用户验证码通过
    showSuccessToast(data.message);

    //跳转第三个页面
    router.push('/login')

}

// 侦听验证码, 控制 提交验证码 按钮能否使用
const btnFlage: Ref<boolean> = ref(true)
watch(
    [ password, repassword ],
    () => {

        if (password.value === '' || repassword.value === '') {
            btnFlage.value = true
        } else {
            btnFlage.value = false
        }

        if (password.value !== repassword.value) {
            btnFlage.value = true
        } else {
            btnFlage.value = false
        }
        
    },
    {
        immediate: true
    }
)
</script>